package com.buildings.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Display;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.buildings.bean.FileTraversal;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by moyun on 2016/1/27.
 */
public class Util {

    public static List<FileTraversal> LocalImgFileList(Context context) {
        List<FileTraversal> data = new ArrayList<FileTraversal>();

        // 获取所有图片文件路径集合
        List<String> allImageFile = listAlldir(context);
        if (allImageFile != null) {
            for (String imgFile : allImageFile) {

                // 获取文件夹名
                String parentFileName = getParentFileName(imgFile);
                // 先根据文件夹名filename创建一个ft对象
                FileTraversal newft = new FileTraversal();
                newft.filename = parentFileName;
                // 判断集合中是否有ft对象,同时获取集合中索引位置
                // ArrayList的indexOf内部判断是利用equals,所以复写对象的equals方法其中判断文件夹名是否相等
                int index = -1;
                if ((index = data.indexOf(newft)) != -1) {
                    // 如果已经添加过该目录下文件,则直接获取其中的集合在其中添加文件
                    FileTraversal ft = data.get(index);
                    ft.filecontent.add(imgFile);
                } else {
                    // 如果未添加过该目录,则将新建ft对象里中再添加文件信息,最后添加到集合中
                    newft.filecontent.add(imgFile);
                    data.add(newft);
                }
            }
        }

        return data;
    }

    /**
     * 获取全部图片地址
     *
     * @return
     */
    public static ArrayList<String> listAlldir(Context context) {
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        Uri uri = intent.getData();
        ArrayList<String> list = new ArrayList<String>();
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, proj, null,
                null, null);// managedQuery(uri, proj, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String path = cursor.getString(0);
                list.add(new File(path).getAbsolutePath());
            }
        }
        if (cursor != null) {
            cursor.close();
        }
        return list;
    }

    /**
     * 获取文件目录名
     *
     * @param data 当前文件的绝对路径
     */
    public static String getParentFileName(String data) {
        String filename[] = data.split("/");
        if (filename != null) {
            return filename[filename.length - 2];
        }
        return null;
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getHeight();
    }

    /***
     * 将dp转换成xp
     */
    public static int Dp_To_XP(Context context, int paramFloat) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (paramFloat * scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue
     * @param dipValue （DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static boolean isEmpty(String str) {
        return str == null || "".equals(str.trim())
                || "null".equals(str.trim());
    }

    /**
     * 隐藏软键盘
     *
     * @param editText
     * @param context
     */
    public static void closeKeyBoard(EditText editText, Context context) {
        ((InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    //此方法只是关闭软键盘
    public static void hintKbTwo(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && activity.getCurrentFocus() != null) {
            if (activity.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 显示软键盘
     *
     * @param editText
     * @param context
     */
    public static void outPutKeyBoard(EditText editText, Context context) {
        editText.requestFocus();
        InputMethodManager inputManager = (InputMethodManager) editText
                .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 是否安装应该
     *
     * @param context
     * @param packagename
     * @return
     */
    public static boolean isAppInstalled(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(
                    packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            // System.out.println("没有安装");
            return false;
        } else {
            // System.out.println("已经安装");
            return true;
        }
    }

//    public static LatLng getBdLatLng(double latitude, double longitude) {
//        LatLng latLng = new LatLng(latitude, longitude);
//        CoordinateConverter converter = new CoordinateConverter();
//        converter.from(CoordType.COMMON);
//        // sourceLatLng待转换坐标
//        converter.coord(latLng);
//        LatLng desLatLng = converter.convert();
//        return desLatLng;
//
//    }

    /**
     * 播放本地视频
     *
     * @param context
     * @param uri
     */
    public static void playVedio(Context context, Uri uri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "video/mp4");
        context.startActivity(intent);
    }

    /**
     * 获取uuid
     *
     * @return
     */
    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String uniqueId = uuid.toString();
        return uniqueId;
    }

    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static void saveMapBitmap(Bitmap bm, String fileName, Context context) throws IOException {
        String path = getMapBitmapFilePath(context);
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

    /**
     * 定位地图截图图片存储文件夹
     *
     * @param context
     * @return
     */
    public static String getMapBitmapFilePath(Context context) {
        String path = Environment.getExternalStorageDirectory().toString() + "/Android/data/" + context.getPackageName() + "/chattemp/";
        return path;
    }

    /**
     * 下载图片
     *
     * @param url
     * @param context
     */
    public static void downImage(final String filePath, final String url, final Context context) {
        new Thread(new Runnable() {

            @Override
            public void run() {

                try {

                    File dirFile = new File(filePath);
                    if (!dirFile.exists()) {
                        dirFile.mkdirs();
                    }
                    File file = new File(filePath + getFileName(url));
                    if (!file.exists()) {
                        if (Util.isNetworkConnected(context)
                                && !TextUtils.isEmpty(url)) {
                            try {
                                URL myFileUrl = new URL(url);
                                // 记住使用的是HttpURLConnection类
                                HttpURLConnection conn = (HttpURLConnection) myFileUrl
                                        .openConnection();
                                conn.setRequestMethod("GET");
                                conn.setConnectTimeout(5 * 1000);
                                conn.setDoInput(true);
                                conn.connect();
                                InputStream is = conn.getInputStream();
                                FileOutputStream fos = new FileOutputStream(
                                        file);
                                byte[] buffer = new byte[1024];
                                int len = 0;
                                while ((len = is.read(buffer)) != -1) {
                                    fos.write(buffer, 0, len);
                                }
                                is.close();
                                fos.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    Intent scanIntent = new Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    scanIntent.setData(Uri.fromFile(file));
                    context.sendBroadcast(scanIntent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    private static String getFileName(String url) {
        return Util.getMD5Code(url) + ".jpg";
    }

    /**
     * 获取字符串的MD5值
     *
     * @param inputString
     * @return
     */
    public static String getMD5Code(String inputString) {
        if (inputString == null || "".equals(inputString)) {
            return "";
        }
        byte[] btInput = inputString.getBytes();
        MessageDigest mdInst = null;
        try {
            mdInst = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        mdInst.update(btInput);
        byte[] md = mdInst.digest();
        StringBuffer sb = new StringBuffer();
        int val;
        for (byte i = 0; i < md.length; i++) {
            val = ((int) md[i]) & 0xff;
            if (val < 16)
                sb.append("0");
            sb.append(Integer.toHexString(val));
        }
        return sb.toString();
    }

    /**
     * 判断是否有网络连接
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

}
